/**
 * Created by YXLF on 2016/5/22.
 */
(function(E, KIT, RES) {
  //region private

  var modelFieldDGVUrl = RES.URL_ROOT + "/dataModel/getDataModelFields";
  var modelUDMKeyGDVUrl = RES.URL_ROOT + "/dataModel/getUDMKeys";
  var element ;
  var __RECEIVE_COMMANDS = function (data,impdata) {

    return {
      "ERRORIMP": function (msg) {
        rapid("#wndPowerfulImportjd").window().hide();
        rapid.fail(msg, function () {

        });
      },
      "FAILIMP": function (msg) {
        rapid("#wndPowerfulImportjd").window().hide();

      },
      "UNREQUESTIMP": function (data) {

        rapid("#wndPowerfulImportjd").window().hide();
      },
      "MSGINFOIMP": function (data) {

        rapid("#wndPowerfulImportjd").window({
          title: "导入中",
          size: "sm",
          onInit: function() {
            $("#wndPowerfulImportjd").parent().parent().parent().find("[data-r-type='button']").remove();
            $("#wndPowerfulImportjd").parent().parent().parent().find("button").replaceWith("<br/><br/><br/>");
          },
          onShow: function() {

            rapid.post({
              url: RES.URL_ROOT + "/dataModel/powerImport",
              data: impdata,
              success: function(result) {
                rapid("#wndPowerfulImportjd").window().hide();

              },
              complete: function() {

                $("#powImportUploader").g_webuploader().clearHtml();
              }
            });
            rapid("#wndPowerfulImport").window().hide();

          },
          onHide: function() {

          }
        }).show();


        element.progress('imp', data+'%');

      }
    };
  }
  var modelFieldDesc = {
    "VARCHAR(100)": "普通字符串",
    "VARCHAR(400)": "大字符串",
    "VARCHAR(2000)": "文本型",
    "CLOB": "富文本型",
    "CHAR(1)": "单字符型",
    "datetime": "日期型",
    "int(18)": "整数型",
    "decimal(18,2)": "数值型"
  };

  /**
   * 模型管理初始化
   */
  var initDataModel = function() {

    var data = [];

    rapid.post({
      url: RES.URL_ROOT + "/dataModel/loadDataModelTree",
      success: function(rs) {

        data = rs;

        var mind = {
          meta: {
            name: 'dataModel'
          },
          /* 数据格式声明 */
          format: 'node_array',
          data: data
        };

        var options = {
          container: 'jsmind_container',
          editable: false,
          theme: 'greensea',
          support_html: true,
          mode: 'side',
          view: {
            hmargin: 100,        // 思维导图距容器外框的最小水平距离
            vmargin: 50,         // 思维导图距容器外框的最小垂直距离
            line_width: 2,       // 思维导图线条的粗细
            line_color: '#555'   // 思维导图线条的颜色
          },
          layout: {
            hspace: 30,          // 节点之间的水平间距
            vspace: 30,          // 节点之间的垂直间距
            pspace: 13           // 节点收缩/展开控制器的尺寸
          },
          shortcut: {
            enable: false,        // 是否启用快捷键
            handles: {},          // 命名的快捷键事件处理器
            mapping: {            // 快捷键映射
              addchild: 45,       // <Insert>
              addbrother: 13,     // <Enter>
              editnode: 113,      // <F2>
              delnode: 46,        // <Delete>
              toggle: 32,         // <Space>
              left: 37,           // <Left>
              up: 38,             // <Up>
              right: 39,          // <Right>
              down: 40            // <Down>
            }
          }
        };

        var jm = new jsMind(options);

        $("#jsmind_container").data("jmObject", jm);

        // 让 jm 显示这个 mind 即可
        jm.show(mind);
      }
    });

  };

  function _getModelEditDv() {
    return rapid("#frmModelEdit").dataview();
  }

  function _initDataview() {
    rapid("#frmModelEdit").dataview({
      colSize: 2,
      paramFields: [{
        name: "conflict_id"
      }],
      fields: [
        {
          title: "模型名称", name: "NAME", id: "txtPartyNamePartyEdit",
          editor: {
            validator: {
              rules: {
                // 规则必填....
                required: true,
                maxnlength: 50
              }
            }
          }
        },
        {
          title: "模型描述", name: "CNNAME",
          editor: {
            validator: {
              rules: {
                // 规则必填....
                required: true,
                maxnlength: 50
              }
            }
          }
        },
        {
          title: "支持版本", name: "IS_VERSION", type: "picker",
          editor: {
            defaultValue: "1",
            defaultText: "是",
            dataSource: [{"value": "1", "text": "是"}, {"value": "0", "text": "否"}]
          }
        },
        {
          title: "是否根模型", name: "ROOT_PARTY_FLG",
          editor: {
            type: "picker",
            validator: {
              rules: {
                required: true
              }
            },
            defaultValue: "1",
            defaultText: "是",
            dataSource: [{"value": "1", "text": "是"}, {"value": "0", "text": "否"}]
          }
        },
        {
          title: "父模型", name: "PAR_PARTY_ID",
          editor: {
            type: "picker",
            defaultValue: "100",
            defaultText: "无"
          }
        },
        {
          title: "模型类别", name: "PARTY_TYPE_CD",
          editor: {
            type: "picker",
            dataSource: {
              textField: "codename",
              valueField: "customid",
              url: RES.URL_ROOT + "/dataModel/loadModelType"
            }
          }
        },
        {
          title: "模型大小", name: "PARTY_SIZE",
          editor: {
            type: "picker",
            validator: {
              rules: {
                // 规则必填....
                required: true
              }
            },
            dataSource: {
              textField: "codename",
              valueField: "customid",
              url: RES.URL_ROOT + "/dataModel/loadModelSize"
            }
          }
        },
        {
          title: "排序", name: "SORTNO",
          editor: {
            validator: {
              rules: {
                // 规则必填....
                required: false,
                integer: true,
                min: 0,
                max: 999999999
              }
            }
          }
        },
        {
          title: "备注", name: "DESCN", size: 12,
          editor: {
            validator: {
              rules: {
                // 规则必填....
                required: false,
                maxnlength: 500
              }
            }
          }
        }
      ]
    });
  }

  var bindAddModelEvt = function() {

    $("#btnAddModel").on("click", function() {

      rapid("#wndModelEdit").window({
        title: "新增模型",
        size: "xl",
        buttons: {
          "保存": function() {
            var s = this;
            if($("#txtPartyNamePartyEdit").val().length < 5) {
              rapid.warning("模型名称不能少于五位的英文字母与下划线组成。");
              return;
            }
            var __dataview = _getModelEditDv();

            if(!__dataview.valid()) {
              return;
            }
            var data = __dataview.serializeJson();
            rapid.post({
              url: RES.URL_ROOT + "/dataModel/saveModel",
              data: data,
              success: function(result) {
                s.hide();
                $("#jsmind_container").empty();
                initDataModel();
              }
            });
          }
        },
        onShow: function() {
          var $_node = $("#jsmind_container").data("jmObject").get_selected_node();

          var __dv = _getModelEditDv();
          if($_node != null) {
            __dv.ui("PAR_PARTY_ID").value($_node.id).text($_node.topic);
          }
          __dv.ui("PAR_PARTY_ID").disabled(true);
        },
        onHide: function() {
          _getModelEditDv().reset();
          //KIT.fillForm("#frmModelEdit", null);
        }
      }).show();
    });
  };

  var bindRemoveModelEvt = function() {

    $("#btnRemoveModel").on("click", function() {
      var $_node = $("#jsmind_container").data("jmObject").get_selected_node();
      if($_node != null) {
        if($_node.id != null && $_node.id != "100") {
          rapid.confirm("删除模型将会删除物理表，包括所有子模型的物理表，是否确认删除？", function(e, rs) {
            if(rs) {
              rapid.post({
                url: RES.URL_ROOT + "/dataModel/removeModel",
                data: "partyKey=" + $_node.id,
                success: function() {
                  $("#jsmind_container").empty();
                  initDataModel();
                  //__initQuerySelectHtml();
                }
              });
            }
          });
        } else {
          rapid.warning("请选中需要删除的模型。");
        }
      } else {
        rapid.warning("请选中需要删除的模型。");
      }
    });

  };

  var bindjmModelDblclick = function() {
    $("#jsmind_container").on("dblclick", "[nodeid]", function() {
      var $_node = $("#jsmind_container").data("jmObject").get_selected_node();

      if($_node.id != null && $_node.id != "100") {

        $("#hidPartyId").val($_node.id);

        rapid("#winDataModelField").window({
          title: "【" + $_node.topic + "】 ",
          size: "max",
          onShow: function() {

            $("#hdnModelName").val($_node.topic);

            /* dgvModelFieldListRefresh($_node.id);*/

            rapid("#grd").grid().tag("model_ids", $_node.id);
            rapid("#grd").grid().load({
              data: {
                modelId: $_node.id,
                state: rapid.ui("#pkState").val(),
                attrNum: rapid.ui("#txtAttrNum").val()
              }
            });

            rapid.post({
              url: RES.URL_ROOT + "/dataModel/getPartyById",
              data: "conflictId=" + $("#hidPartyId").val(),
              success: function(result) {
                $("#hidPartySize").val(result.party_size);
                $("#spnModelNameKey").val(result.name); //后面设置主键页面需要的当前模型表名称
              }
            });

          },
          onHide: function() {
            rapid.ui("#pkState").val(null);
            rapid.ui("#txtAttrNum").val(null);
            $("#hdnModelName").val("");
            $("#hidPartyId").val("");
          }
        }).show();
      }
    });
  };

  //region GID编辑
  var _update = function(e) {
    var __grid = this;

    rapid.confirm("确定要保存吗？", function(yes) {
      if(yes) {
        rapid.post({
          url: RES.URL_ROOT + "/dataModel/updateDataModel",
          data: e.serializeJson(),
          success: function(result) {
            e.hide();
            rapid.success("保存成功。", function() {
              __grid.reload();
            }, false);
          }
        });
      }
    });
  };

  var _add = function(e) {
    var __grid = this;

    rapid.confirm("确定要保存吗？", function(yes) {
      if(yes) {
        var _modelName = $("#hdnModelName").val();
        var _model_descn = _modelName.split("|")[1];
        rapid.post({
          url: RES.URL_ROOT + "/dataModel/addDataModel",
          data: $.extend({}, e.serializeJson(), {model_id: $("#hidPartyId").val(), model_name: _model_descn}),
          success: function(result) {
            e.hide();
            rapid.success("保存成功。", function() {
              __grid.reload();
            }, false);
          }
        });
      }
    });
  };

  var dgvAttrSetEvent = function() {
    $("#dataModelFieldList").on("click.njdt_edit", ".fn-set-field", function() {

      var _fieldId = rapid.ui(this).tag("fieldid");
      var _attrib_name = rapid.ui(this).tag("attrib_name");
      var _attrib_descn = rapid.ui(this).tag("attrib_desc");
      if(typeof (_attrib_descn) == 'undefined') {
        _attrib_descn = "";
      }

      rapid("#winDataModelFieldEdit").window({
        title: "编辑【" + _attrib_name + " | " + _attrib_descn + "】字段属性",
        buttons: {
          "保存": function() {
            var _this = this;

            var __dataview = _getFieldEditDv();

            if(!__dataview.valid()) {
              return;
            }

            var data = __dataview.serializeJson();
            rapid.post({
              url: RES.URL_ROOT + "/dataModel/updateDataModel",
              data: data,
              success: function(result) {
                _this.hide();
                dgvModelFieldListRefresh();
              }
            });
          }
        },
        onShow: function() {

          rapid.post({
            url: RES.URL_ROOT + "/dataModel/getDataModelById",
            data: "Id=" + _fieldId,
            success: function(result) {
              var __dv = _getFieldEditDv();
              __dv.bind(result);
              if(!rapid.isEmpty(result.code_name)) {
                $("#txtCodeName").selectorbox().val(result.code_name).text(result.code_name);
              }
            }
          });
        },
        onHide: function() {
          _getFieldEditDv().reset();
          $("#txtCodeName").selectorbox().backDefault();
        }
      }).show();

    });
  };

  var dgvAttrRemoveEvent = function() {
    $("#dataModelFieldList").on("click.njdt_remove", ".fn-remove-field", function() {

      var _fieldId = rapid.ui(this).tag("fieldid");
      var _item = rapid("#dataModelFieldList").table().item(_fieldId);

      if(validFieldName(_item.ATTRIB_NAME, $("#hidPartySize").val())) {
        rapid.confirm("确认删除这个字段吗？", function(e, rs) {
          if(rs) {
            rapid.post({
              url: RES.URL_ROOT + "/dataModel/removeDataModel",
              data: "ID=" + _fieldId,
              success: function(result) {
                dgvModelFieldListRefresh();
              }
            });
          }
        });
      } else {
        rapid.warning("只能删除自定义新增的列。");
      }
    });

  };

  var dgvAttrResetEvent = function() {
    $("#dataModelFieldList").on("click.njdt_reset", ".fn-reset-field", function() {

      var _fieldId = rapid.ui(this).tag("fieldid");

      rapid.confirm("确认重置这个字段吗？", function(e, rs) {
        if(rs) {
          rapid.post({
            url: RES.URL_ROOT + "/dataModel/resetDataModel",
            data: "ID=" + _fieldId,
            success: function(result) {
              dgvModelFieldListRefresh();
            }
          });
        }
      });

    });

  };

  var initBusinessField = function() {

    $("#treeBusinessCode").g_jstree({
      data: {
        url: RES.URL_ROOT + "/dataModel/getjsTreeByBusCodes"
      },
      onselected: function(element, inst, $node) {
        $("#txtCodeName").selectorbox().val($node.id).text($node.id);
        rapid("#winBusinessCode").window().hide();
      }
    });

    $("#txtCodeName").selectorbox({
      name: "code_name",
      onclick: function(obj) {
        rapid("#winBusinessCode").window({
          title: "关联代码",
          size: "sm",
          height: "100%",
          buttons: {
            "清空": function() {
              $("#txtCodeName").selectorbox().val("").text("");
              this.hide();

            }
          },
          onShow: function() {
            $("#treeBusinessCode").g_jstree().opennode($("#treeBusinessCode").g_jstree().getnode("业务代码"));
          }
        }).show();
      }
    });

    $("#btnOpenAllTreeBusCode").bind("click", function() {
      $("#treeBusinessCode").g_jstree().openall();
    });

    $("#btnCloseAllTreeBusCode").bind("click", function() {
      $("#treeBusinessCode").g_jstree().closeall();
    });

  };

  var initDataModelField = function() {
    dgvAttrSetEvent();
    dgvAttrRemoveEvent();
    dgvAttrResetEvent();
    initBusinessField();
  };

  var validFieldName = function(fieldName, partysize) {

    var _prefix = fieldName.substring(0, 7);

    if(_prefix != "ATTRIB_") {
      return false;
    }

    var _size = 0;

    _size = parseInt(fieldName.substring(7));

    if(partysize == "LAR") { //100
      if(_size > 100) {
        return true;
      }

    } else if(partysize == "MID") { //60
      if(_size > 60) {
        return true;
      }

    } else {//20
      if(_size > 20) {
        return true;
      }
    }

    return false;

  };

  //endregion

  //region 主键设置管理

  var initUDMValid = function() {
    rapid.ui("#txtUDMKeyTitle", {
      validator: {
        rules: {
          required: true
        }
      }
    });

    rapid.ui("#attribUDMKeyTypePicker", {
      validator: {
        rules: {
          required: true
        }
      }
    });
  };

  var bindSetUDMKeyEvent = function() {
    $("#btnSetUDMKey").on("click", function() {
      rapid("#winDataModelUDMKey").window({
        title: "设置【" + $("#hdnModelName").val() + "】主键",
        size: "xl",
        onShow: function() {
          rapid("#gridUDMKey").grid().load({data: {modelId: $("#hidPartyId").val()}});
        },
        onHide: function() {
          KIT.fillForm("#frmModelUDMKeyEdit", null);
        }
      }).show();

    });
  };

  var bindUDMKeyAddEvent = function() {
    $("#btnSetUDMKeyAdd").on("click", function() {
      rapid("#frmModelUDMKeyEdit").window({
        title: "请选择一项或多项",
        size: "sm",
        buttons: {
          "保存": function() {
            var _this = this;
            if(!rapid.ui("#txtUDMKeyTitle").valid()) {
              return false;
            }
            if(!rapid.ui("#attribUDMKeyTypePicker").valid()) {
              return false;
            }
            var attribValue = rapid("#attribUDMKeyTypePicker").picker().value();
            if(rapid.isEmpty(attribValue)) {
              rapid.warning("请选择字段类型作为主键！");
            }

            rapid.post({
              url: RES.URL_ROOT + "/dataModel/saveUDMKey",
              data: {
                modelId: $("#hidPartyId").val(),
                title: rapid.ui("#txtUDMKeyTitle").val(),
                attribs: attribValue
              },
              success: function(result) {
                _this.hide();
                rapid("#gridUDMKey").grid().load({data: {modelId: $("#hidPartyId").val()}});
              }
            });

          }
        },
        onHide: function() {
          KIT.fillForm("#frmModelUDMKeyEdit", null);
        }
      }).show();

    });

  };

  var initUDMKeyIndex = function() {
    bindSetUDMKeyEvent();
    bindUDMKeyAddEvent();
    initUDMValid();
  };

  //endregion

  //region 初始化万能导入

  /*  var initPowerfulImport = function() {

   rapid.kit.initPowerfulImportPanel();

   $("#btnpowImport").on("click", function() {
   var _tableName = "";
   var $_node = $("#jsmind_container").data("jmObject").get_selected_node();
   if(!rapid.isEmpty($_node)) {
   if(!rapid.isEmpty($_node.topic.toString())) {
   var _arr = $_node.topic.toString().split("|");
   if(rapid.isArray(_arr)) {
   _tableName = _arr[0];
   }
   }
   }
   rapid.kit.openPowerfulImportPanel({selectorTableName: _tableName});
   });
   }*/
  var initPowerfulImport = function() {
    _initWindow();
    _initButton();
    _initWebUploader();
    initImportPicker();
    _initVaild();

  }
  var _initButton = function() {
    rapid.ui("#btnpowImport").on("click", function() {
      rapid("#wndPowerfulImport").window().show();
    });

  }

  function _initWindow() {
    //region万能导入
    rapid("#wndPowerfulImport").window({
      title: "万能导入",
      buttons: {
        "导入": function(s, t) {
          var _this = this;
          if(!_startVaild()) {
            return;
          }
          var fileName = $("#frmPowerfulImport").find("input[name='hideFileName']").val();
          if(rapid.isEmpty(fileName)) {
            rapid.warning("请上传要导入的数据！");
            return false;
          }

          rapid.confirm("确定要导入吗？", function(e, r) {
            if(!e) {
              return;
            }
            var impdata = $("#frmPowerfulImport").r_serializeJson();

            impdata.modelId = rapid.ui("#pkrModelTable").val() + "";
            impdata.umdKey = rapid.ui("#pkrUdkey").val() + "";
            impdata.fnformid = rapid.ui("#pkrFnForm").val() + "";
            impdata.updateRule = rapid.ui("#pkrUpdateRule").val() + "";
            impdata.importFile = fileName;
            element.progress('imp', '0%');
            var ws,__WS_URL;

            rapid.post({
              url: RES.URL_ROOT + "/dataModel/getImpWebsocketUrl",
              data:impdata,
              success: function (data) {

                __WS_URL = data.url;

                ws = rapid.WebSocket({
                  url: __WS_URL,
                  cmdFormat: {
                    id: "name",
                    data: "data"
                  },
                  commands: rapid.extend(__RECEIVE_COMMANDS(this,impdata), {})
                }).on("message", function (msg) {


                });

                ws.on("connect", function () {

                  this.send(KIT.cmd("IMP", {userId: data.userid}));

                }).on("serverClose", function () {

                  console.log("serverClose");
                }).on("error", function () {

                  console.log("error");
                }).connect();


              },fail:function () {
                $("#powImportUploader").g_webuploader().clearHtml();
              }

            });
          });
        }
      },
      onShow: function() {
        rapid.kit.fillForm("#frmPowerfulImport", null);
        var $_node = $("#jsmind_container").data("jmObject").get_selected_node();
        if(!rapid.isEmpty($_node) && !rapid.isEmpty($_node.id)) {
          rapid.post({
            url: RES.URL_ROOT + "/dataModel/getModelTableByPicker",
            data: "modelId=" + $_node.id,
            success: function(result) {
              if(!rapid.isEmpty(result) && result.length > 0) {
                rapid("#pkrModelTable").picker().value(result[0].value).text(result[0].text).disabled(true).trigger("change");
              }
            }
          });
        }
      },
      onHide: function() {
        rapid.kit.fillForm("#frmPowerfulImport", null);
        rapid("#pkrModelTable").picker().val(null).disabled(false);
        rapid("#pkrUdkey").picker().val(null).disabled(true);
        $("#powImportUploader").g_webuploader().clearHtml();
      }
    });
    //endregion
  };

  //初始化上传控件
  var _initWebUploader = function() {
    $("#powImportUploader").g_webuploader({
      uploadType: "file",
      accept: {
        title: 'File',
        extensions: 'xls,XLS,xlsx,XLSX',
        mimeTypes: 'application/xls,application/xlsx'
      },
      name: "importFile",
      ratio: 1.2,
      multiple: false,
      hideFileName: true,
      server: RES.URL_ROOT + "/dataModel/updateXlsFile",
      onUploadSuccess: function(file, response) {
        if(rapid.isUndefined(response)) {
          rapid.warning("系统异常，请刷新。");
          return false;
        }
        if(!rapid.isEmpty(response.message)) {
          rapid.warning(response.message, true);
        }
        if(response.state == 1) {

          var file = $("#frmPowerfulImport").find("input[name='hideFileName']");

          if((typeof (file) == "undefined") || file.length == 0) {
            var _html = "<input type='hidden' name='hideFileName' value='" + response.data + "'/>";
            $("#powImportUploader #powImportUploader_filelist").append(_html);
          } else {
            file.val(response.data);
          }
        }
      }
    });
  };

  //万能导入picker
  var initImportPicker = function() {
    rapid("#pkrModelTable").picker({
      dataSource: {
        url: RES.URL_ROOT + "/dataModel/getModelTableByPicker"
      },
      tip: "选择模型表..."
    }).on("change", function() {
      _setSubGroupPicker(this.value(), rapid("#pkrUdkey").picker());
    });

    rapid("#pkrUdkey").picker({
      disabled: true,
      dataSource: {
        url: RES.URL_ROOT + "/dataModel/getModelUDMkeyByPicker"
      },
      tip: "选择导入主键..."
    });

    rapid("#pkrUpdateRule").picker({
      dataSource: {
        url: RES.URL_ROOT + "/dataModel/getRuleCode"
      },
      tip: "选择更新规则..."
    });

    rapid("#pkrFnForm").picker({
      autoReload: true,
      dataSource: {
        textField: "name",
        valueField: "id",
        type: "post",
        url: RES.URL_ROOT + "/formdesigner/findForm",
        data: "type=1"
      },
      tip: "选择动态表单..."
    });

  }

  var _initVaild = function() {

    rapid.ui("#pkrModelTable", {
      validator: {
        rules: {
          required: true
        }
      }
    });
    rapid.ui("#pkrUdkey", {
      validator: {
        rules: {
          required: true
        }
      }
    });
    rapid.ui("#pkrUpdateRule", {
      validator: {
        rules: {
          required: true
        }
      }
    });

    /* rapid.ui("#pkrSalesPromotionId", {
     validator: {
     rules: {
     required: true
     }
     }
     });*/
  }

  var _startVaild = function() {
    if(!rapid.ui("#pkrModelTable").valid()) {
      return false;
    }
    if(!rapid.ui("#pkrUdkey").valid()) {
      return false;
    }
    if(!rapid.ui("#pkrUpdateRule").valid()) {
      return false;
    }
    return true;
  }

  var _setSubGroupPicker = function() {
    // 每当改变了父项，则清空子项，
    // 若没有选择任何父项，则禁用子项

    var _len = arguments.length;

    if(_len == 2) {
      arguments[1].val(null);

      if(rapid.isEmpty(arguments[0])) {
        arguments[1].disabled(true);

      } else {
        arguments[1].disabled(false)
                    .dataSource({
                      data: "modelId=" + arguments[0]
                    });
      }
    } else {
      arguments[2].val(null);

      if(rapid.isEmpty(arguments[0])) {
        arguments[2].disabled(true);

      } else {
        arguments[2].disabled(false)
                    .dataSource({
                      data: {
                        CUSTOMID: arguments[0],
                        CUSTOMIDPERENT: arguments[1]
                      }
                    });
      }
    }

  };

  //region 初始化万能导出

  var initExportCst = function() {
    _initExportWin();
    _initExportTableList();
    _initExportBtn();
    _initExportPicker();

  }
  var _initExportBtn = function() {
    $("#exportModel").on("click", function() {
      rapid("#wndPowerfulExport").window().show();
    });
    $("#btnExportData").on("click", function() {
      var _srows = rapid("#tableListExport").table("selections");
      if(!rapid.isEmpty(_srows)) {
        var _keys = [];
        for(var i = 0; i < _srows.length; i++) {
          _keys.push(_srows[i].id);
        }

        rapid.confirm("是否确定导出？", function(e, r) {
          if(e) {
            rapid.ui("#btnExportData").disabled(true);
            rapid.post({
              url: RES.URL_ROOT + "/dataModel/exportModelName",
              data: "keys=" + _keys.join(","),
              success: function() {
                rapid.success();
                rapid("#wndPowerfulExport").hide();
              },
              complete: function() {
                rapid.ui("#btnExportData").disabled(false);
              }
            });
          }
        });
      } else {
        rapid.warning("请选择要导出的字段！");
      }
    });
  }

  //万能导出窗体
  var _initExportWin = function() {
    //region万能导出窗体
    rapid("#wndPowerfulExport").window({
      title: "万能导出",
      size: "max",
      onShow: function() {
        var $_node = $("#jsmind_container").data("jmObject").get_selected_node();
        if(!rapid.isEmpty($_node) && !rapid.isEmpty($_node.id)) {
          rapid.post({
            url: RES.URL_ROOT + "/dataModel/getModelTableByPicker",
            data: "modelId=" + $_node.id,
            success: function(result) {
              if(!rapid.isEmpty(result) && result.length > 0) {
                rapid("#pkrModelTableExport").picker().value(result[0].value).text(result[0].text).disabled(true).trigger("change");
              }
            }
          });
        } else {
          rapid("#pkrModelTableExport").picker().val(null);
        }
      },
      onHide: function() {
        rapid("#pkrModelTableExport").picker().val(null).disabled(false);
        $("#tableListExport").bootstrapTable("refresh");
      }
    });
    //endregion
  }
  //万能导出picker
  var _initExportPicker = function() {
    rapid("#pkrModelTableExport").picker({
      dataSource: {
        url: RES.URL_ROOT + "/dataModel/getModelTableByPicker"
      },
      tip: "选择模型表...",
      onchange: function() {
        $("#tableListExport").bootstrapTable("refresh", {
          query: {
            modelId: this.value()
          }
        });
      }
    });
  }

  //初始化万能导出窗体
  var _initExportTableList = function() {
    rapid("#tableListExport").table({
      url: RES.URL_ROOT + "/dataModel/getExportList",
      selectable: true,
      keyField: "id",
      //  height:height,
      queryParams: function(params) {
        var modelId = rapid("#pkrModelTableExport").picker().value();
        return $.extend(true, {}, params, {modelId: modelId});
      },
      onLoadSuccess: function() {
        //rapid.success("11",function(){
        $(window).trigger("resize");
        //rapid("#winDataModelField").window().resize();
        // });
      },
      columns: [{
        checkbox: true
      }, {
        title: '字段名',
        field: "attrib_name",
        formatter: function(value, row, index) {
          return rapid.kit.html.highlight(value);
        }
      }, {
        title: '字段描述',
        field: "attrib_descn",
        formatter: function(value, row, index) {
          return rapid.kit.html.highlight(value);
        }
      }, {
        title: '字段类型',
        field: "attrib_type"
      }, {
        title: '字段类型描述',
        field: "attrib_type_desc"
      }, {
        title: '状态',
        field: "state",
        formatter: function(value, row, index) {
          if('1' == value) {
            return "锁定";
          } else {
            return "激活";
          }
        }
      },
        {
          title: '添加方式',
          field: "hand_flg",
          formatter: function(value, row, index) {
            if('1' == value) {
              return "手动";
            } else {
              return "自动";
            }
          }
        }]
    });
  }

  //endregion

  //endregion

  rapid.Page.create(
    {
      methods: {
        //region 模型字段grid
        _getGridSingeActions_: function() {
          var __app = this;

          return [{
            "重置": function() {
              __app._openMenuPermissionByRole_(this.selection()[0].ui().id.val());
            }
          }, {
            "删除": function() {

              var __s = this;
              rapid.confirm("确认重置这个字段吗？", function(e, rs) {
                if(rs) {
                  rapid.post({
                    url: RES.URL_ROOT + "/dataModel/removeDataModel",
                    data: "ID=" + __s.selection()[0].ui().id.val(),
                    success: function(result) {
                      rapid("#grd").grid().reload();
                    }
                  });
                }
              });
            }
          }];
        },
        _getGridFields_: function() {
          return [{
            title: "所属模型", name: "model_name", width: 200, visible: false
          }, {
            title: "字段名", name: "attrib_name", width: 100
          }, {
            title: "字段描述", name: "attrib_descn", size: 12,
            editor: {
              validator: {
                rules: {
                  required: true,
                  maxnlength: 50
                }
              }
            }
          }, {
            title: "字段类型", name: "attrib_type", width: 150,
            editor: {
              type: "picker",
              tip: "请选择字段类型...",
              validator: {
                rules: {
                  required: true
                }
              },
              dataSource: {
                url: RES.URL_ROOT + "/dataModel/getFieldTypeResouceAdd"
              },
              onchange: function(e) {
                if(rapid.isEmpty(this.value())) {
                  e.ui("attrib_type_desc").val(null)
                } else {
                  e.ui("attrib_type_desc").val(modelFieldDesc[this.value()]);
                }
              }
            }
          }, {
            title: "字段类型描述", name: "attrib_type_desc", width: 120
          }, {
            title: "数据是否加密", name: "encry_flg", visible: false, editor: {
              name: "encry_flg", type: "radiolist", defaultValue: 1,
              dataSource: [{text: "是", value: 1}, {text: "否", value: 0}]
            }
          }, {
            title: '状态', name: "state_cn", width: 60, serializable: false

          }, {
            title: "关联代码", name: "code_name", width: 250,
            formatter: function(v) {
              if(!rapid.isEmpty(v)) {
                return v.split('|')[0];
              }
              return "";
            },
            editor: {
              type: "picker",
              tip: "请选择...",
              dataSource: {
                url: RES.URL_ROOT + "/code/getCodeTopInfo"
              },
              onchange: function(e) {
                if(rapid.isEmpty(this.value())) {
                  e.ui("code_leaf").val(null).disabled(true);
                } else {
                  if(rapid.isEmpty(e.ui("code_leaf").val())) {
                    e.ui("code_leaf").val(2);
                  }
                  e.ui("code_leaf").disabled(false);
                }
              }
            }
          }, {
            title: "关联级别", name: "code_leaf", width: 80,
            editor: {
              disabled: true,
              validator: {
                rules: {
                  integer: true,
                  min: 2,
                  max: 10
                }
              }
            }
          }, {
            title: "备注", name: "remark", size: 12, width: 200,
            editor: {
              validator: {
                rules: {
                  maxnlength: 50
                }
              }
            }
          }];
        },

        _initGridEvent_: function() {
          this.tag("grid")
              .on("add", _add)
              .on("update", _update)
              .on("beforeUpdate", function(e) {
                var __grid = this;

                if(!rapid.isEmpty(__grid.current().ui().code_leaf.val())) {
                  e.ui("code_leaf").disabled(false);
                }

                if(__grid.current().ui().hand_flg.val() != "1") {
                  e.ui("attrib_type").disabled(true);
                } else {
                  e.ui("attrib_type").disabled(false);
                }

              });
        },

        _initGrid_: function() {
          var __app = this;
          this.tag("grid", rapid("#grd").grid({
            height: function() {
              return $(__app.main()).height() - 100;
            },
            addable: true,
            updatable: true,
            detailed: true,

            dataSource: {
              url: modelFieldDGVUrl
            },
            pageable: true,
            keyFields: "id",
            paramFields: ["id", "model_id", "hand_flg"],
            fields: this._getGridFields_(),
            singleActions: this._getGridSingeActions_()
          }));

          this._initGridEvent_();
        },

        _openMenuPermissionByRole_: function(id) {
          // var _fieldId = rapid.ui(this).tag("fieldid");
          var __s = this;
          rapid.confirm("确认重置这个字段吗？", function(e, rs) {
            if(rs) {
              rapid.post({
                url: RES.URL_ROOT + "/dataModel/resetDataModel",
                data: "ID=" + id,
                success: function(result) {
                  rapid("#grd").grid().reload();
                }
              });
            }
          });

        },
        //endregion

        //region 主键grid udkey

        _getUDMKeyGridFields_: function() {
          return [{
            title: "模型名称", name: "name", width: 100
          },
            {
              title: "标题说明", name: "attrib_01", width: 100
            }, {
              title: "主键字段名", name: "attrib_02", width: 250
            },
            {
              title: "主键字段描述", name: "attrib_03", width: 250
            }];
        },

        _initUDMKeyGridEvent_: function() {
          this.tag("gridUDMKey")
              .on("remove", function(ids) {
                var __grid = this;
                rapid.post({
                  url: RES.URL_ROOT + "/dataModel/removeUDMKey",
                  data: "conflictIds=" + ids,
                  success: function() {
                    __grid.reload();
                  }
                });
              });
        },

        _initUDMKeyGrid_: function() {
          var __app = this;
          this.tag("gridUDMKey", rapid("#gridUDMKey").grid({
            height: 400,
            removable: true,
            detailed: true,
            dataSource: {
              url: modelUDMKeyGDVUrl
            },
            pageable: true,
            keyFields: "conflict_id",
            paramFields: ["conflict_id"],
            fields: this._getUDMKeyGridFields_()
          }));

          this._initUDMKeyGridEvent_();
        },
        //endregion
        _initUi_: function() {
          var __app = this;

          //查询
        }
      }
    }
  )(function() {
    rapid("#pkState").picker({
      dataSource: [
        {text: "已锁定", value: "1"},
        {text: "未锁定", value: "0"}
      ],
      onchange: function() {
        rapid.ui("#txtAttrNum").val(null);
        var __grd = rapid("#grd").grid();

        __grd.load({
          data: {
            modelId: __grd.tag("model_ids"),
            state: this.value()
          }
        });
      }
    });

    rapid.ui("#txtAttrNum").on("change", function() {
      rapid.ui("#pkState").val(null);
      var __grd = rapid("#grd").grid();

      __grd.load({
        data: {
          modelId: __grd.tag("model_ids"),
          attrNum: this.value()
        }
      });
    });

    rapid.ui("#attribUDMKeyTypePicker").settings({
      autoReload: true,
      multiple: true,
      dataSource: {
        url: RES.URL_ROOT + "/dataModel/getDataModelUDMKeyList",
        data: function() {
          return "modelId=" + $("#hidPartyId").val();
        }
      },
      autocomplete: {
        dataSource: {
          url: RES.URL_ROOT + "/dataModel/getDataModelUDMKeyList",
          data: function(v) {
            return {
              name: v,
              modelId: $("#hidPartyId").val()
            };
          }
        }
      }
    });

    this._initGrid_();
    this._initUDMKeyGrid_();
    initDataModel();
    _initDataview();
    bindAddModelEvt();
    bindRemoveModelEvt();
    initDataModelField();
    bindjmModelDblclick();
    initUDMKeyIndex();
    initPowerfulImport();
    //initExportCst();//导出模型

    element = layui.element; //Tab的切换功能，切换事件监听等，需要依赖element模块

  }).init();
})(rapid.html.Element, rapid.kit, rapid.res);